<!-- 登录 -->
<template>
  <div>
    <div class="login_container">
      <!-- 一行里两列 栅格24份-->
      <el-row>
        <!-- xs:0 当屏幕的宽度小于等于768px的时候,不显示(0份) -->
        <el-col :span="12" :xs="0"></el-col>
        <el-col :span="12" :xs="24">
          <!-- 登录的表单 -->
          <el-form class="login" :model="loginForm" :rules="rules" ref="form">
            <h1>Hello</h1>
            <h2>欢迎来到Crop</h2>
            <el-form-item prop="username">
              <!-- :v-model="loginForm.username" 冒号不写-->
              <el-input
                :prefix-icon="User"
                v-model="loginForm.username"
              ></el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                :prefix-icon="Lock"
                v-model="loginForm.password"
                show-password
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button
                @click="login"
                :loading="user.isLoding"
                class="login_btn"
                type="primary"
                size="default"
                color="#48a295"
              >
                登录
              </el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup lang="ts">
import { User, Lock } from '@element-plus/icons-vue'
import { reactive, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
// elements-plus错误提示框
import { ElNotification } from 'element-plus'
import useUserStore from '../../store/modules/user'
import { getTime } from '../../utils/time'
let user = useUserStore()
let $route = useRoute()
let $router = useRouter()
let loginForm = reactive({
  username: 'admin',
  password: '111111',
})
let form = ref()

const validateUserName = (rule: any, value: any, callback: any) => {
  // rule 校验规则对象
  // value 被校验表单元素form-item文本内容
  // 函数 如果符合条件callBack放行通过行为
  if (value.length >= 5) {
    callback()
  } else {
    callback(new Error('账号长度至少5位'))
  }
}
const validatePassWord = (rule: any, value: any, callback: any) => {
  if (value.length >= 6) {
    callback()
  } else {
    callback(new Error('密码长度至少6位'))
  }
}

// 定义表单校验需要的校验对象
const rules = {
  // 规则对象属性:
  // required, 代表这个字段务必要校验
  // trigger, 触发校验表单的时机 change->文本发生变化触发校验;blur->失去焦点
  username: [
    // { required: true, min: 5, max: 10, message: '账号长度5~10位', trigger: 'change' }
    { validator: validateUserName, trigger: 'change' },
  ],
  password: [
    // { required: true, min: 6, max: 15, message: '密码长度6~10位', trigger: 'change' }
    { validator: validatePassWord, trigger: 'change' },
  ],
}

/* click: 登录 */
const login = async () => {
  try {
    // 保证全部表单项校验通过再发请求, promise如果失败阻止进行后面的代码
    await form.value.validate() //如果await的promise失败了，就会抛出异常，需要通过try...catch捕获处理, 成功则执行后面的try...catch登录代码发送请求
    try {
      // let result = user.userLogin(loginForm)
      // console.log(result);
      await user.userLogin(loginForm)
      // 编程式导航跳转到首页
      // 编程式导航跳转到展示数据首页
      // 判断登录的时候,路由路径当中是否有query参数，如果有就往query参数挑战，没有跳转到首页
      let redirect: any = $route.query.redirect
      $router.push({ path: redirect || '/' })
      user.isLoding = false
      ElNotification({
        type: 'success',
        message: '登录成功',
        title: `HI,${getTime()}`,
      })
      window.location.reload()
    } catch (error) {
      user.isLoding = false
      console.log('eooooooooooooooooooor')
      ElNotification({
        type: 'error',
        message: (error as Error).message,
      })
    }
    //表单验证失败执行的逻辑
  } catch (error) {
    ElNotification({
      type: 'warning',
      title: '用户名密码不符合规范',
    })
  }
}
</script>

<style scoped lang="scss">
.login_container {
  width: 100%;
  height: 100vh;
  background: url('@/assets/images/background.jpg') no-repeat;
  background-size: cover;
}

.login {
  position: relative;
  width: 80%;
  top: 30vh;
  background: url('@/assets/images/login_form.png') no-repeat;
  padding: 40px;

  h1 {
    font-size: 40px;
    color: rgb(255, 255, 255);
  }

  h2 {
    font-size: 20px;
    color: rgb(255, 255, 255);
    margin: 20px 0px;
  }

  .login_btn {
    width: 100%;
  }
}
</style>
